//
//  LoginViewController.m
//  登录找回密码
//
//  Created by 于鹏 on 2017/7/25.
//  Copyright © 2017年 于鹏. All rights reserved.
//

#import "XLLoginViewController.h"

#import "UIViewController+DismissKeyboard.h"
#import "Lothar+Main.h"
#import "RongIMKit/RongIMKit.h"
#import "XLRCIMDataBaseManager.h"
#import "XLConfigViewController.h"
//#import <BaseModule/UIViewController+DismissKeyboard.h>
//#import <Main_Category/Lothar+Main.h>
//#import <RongIMKit/RongIMKit.h>

#import "XLForgetPwdViewController.h"
#import "XLEditedButton.h"
#import "XLTextFieldView.h"
#import "YYText.h"
@interface XLLoginViewController ()
@property (weak, nonatomic) IBOutlet XLTextFieldView *usernameTextField;
@property (weak, nonatomic) IBOutlet XLTextFieldView *passwordTextField;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet XLEditedButton *loginButton;
@property (weak, nonatomic) IBOutlet YYLabel *agreementLabel;

@property (nonatomic)int loginFailureTimes;


@end

@implementation XLLoginViewController
#pragma mark - Life Cycle

//+ (XLLoginViewController *)sharedManager {
//    static XLLoginViewController *loginVC = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        loginVC = [[XLLoginViewController alloc]init];
//    });
//    return loginVC;
//}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _loginFailureTimes = 0;

    [self setupForDismissKeyboard];

}

#pragma mark - Override
- (void)initInterface {
    self.usernameTextField.placeHolderText = @"请输入11位中国大陆手机号";
    self.passwordTextField.placeHolderText = @"请输入6~16 位的数字 / 字母密码";
    self.passwordTextField.secureTextEntry = YES;
    
    NSString *str1 = @"登录即已阅读并同意  ";
    NSString *str2 = @"软件许可协议";
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%@",str1,str2]];
    NSRange range = NSMakeRange(str1.length, str2.length);
    [string yy_setUnderlineStyle:NSUnderlineStyleSingle range:range];
    [string yy_setColor:kXLTextColor_WHITE range:NSMakeRange(0, str1.length)];
    UIColor *color = kRGB(217, 217, 217);
    [string yy_setColor:color range:range];
    
//    [string yy_setUnderlineColor:kXLWhiteColor range:range];
    [string yy_setTextHighlightRange:range color:color backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        XLLog(@"点击软件许可协议");
    }];
    
    self.agreementLabel.attributedText = string;
//    self.agreementLabel.textColor = kXLWhiteColor;
    self.agreementLabel.font = XLFONT(14);
    self.agreementLabel.textAlignment = NSTextAlignmentCenter;
    
    self.loginButton.enabled = NO;
}


#pragma mark - Action

- (IBAction)loginAction:(UIButton *)sender {
    if (!UserInfo.serviceInfo.isVaild) {
        [self showInfoWithStatus:@"请先配置服务器!"];
        return;
    }
    [self showWithStatus:@"正在登陆..."];
    sender.enabled = NO;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.usernameTextField.textFieldText forKey:@"userName"];
    [parameters setValue:self.passwordTextField.textFieldText forKey:@"passWord"];
    [parameters setValue:@"ios" forKey:@"typeName"];

//    [parameters setValue:[JPUSHService registrationID] forKey:@"RegistrationId"];
    [XLHTTPRequest UM_loginWithParameters:parameters success:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"1"]) {
            NSDictionary *dic = responseObject[@"data"];
            UserInfo.userID = dic[@"doctorID"];
            UserInfo.userName = dic[@"userName"];
            UserInfo.nickName = dic[@"nickName"];
            UserInfo.phone = dic[@"phone"];
            UserInfo.gender = dic[@"gender"];
            UserInfo.userLogo = dic[@"head"];
            UserInfo.hospital = dic[@"hospitalName"];
            UserInfo.tokenCode = dic[@"token"];
            UserInfo.RYID = dic[@"ryID"];
//            UserInfo.RYName = dic[@"ryName"];//不用这个返回的name赋值
            UserInfo.isLogin = YES;
            [UserInfo synchronize];
            //连接融云
            [self getRY_tokenUserId:UserInfo.userID deviceToken:UserInfo.tokenCode userName:UserInfo.userName userLogo:UserInfo.userLogo sender:sender];
//            [[Lothar shared]main_setTabBarRootViewController];

        } else {
            sender.enabled = YES;
        }
    } failure:^(NSError *error, NSString *info) {
        UserInfo.isLogin = NO;
        sender.enabled = YES;
        if (error == nil) {
            [self exitLogin:info];
        }
    }];
    
}

//连接融云
- (void)getRY_tokenUserId:(NSString *)user_id deviceToken:(NSString *)token userName:(NSString *)userName userLogo:(NSString *)userLogo sender:(UIButton *)sender{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:user_id forKey:@"doctorID"];
    [parameters setValue:token forKey:@"token"];
    [XLHTTPRequest Doctor_getRYTokenWithParameters:parameters success:^(id responseObject) {
        NSString *token = ISNILORNULL(responseObject[@"RY_Token"]);
        [[RCIM sharedRCIM]connectWithToken:token success:^(NSString *userId) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showSuccessWithStatus:@"登录成功！"];
                UserInfo.RYToken = responseObject[@"RY_Token"];
                UserInfo.RYID = userId;
                UserInfo.RYName = userName;
                if (![userLogo isEqualToString:@""]) {
                    UserInfo.RYLogo = [UserInfo.serviceInfo.baseURL stringByAppendingString:userLogo];
                }else {
                    UserInfo.RYLogo = @"";
                }
                [UserInfo synchronize];
                //存储自己的信息
                RCUserInfo *user = [[RCUserInfo alloc]init];
                user.userId = userId;
                user.name = userName;
                user.portraitUri = UserInfo.RYLogo;
                [RCIM sharedRCIM].currentUserInfo = user;
                //插入数据库
                [[XLRCIMDataBaseManager shareInstance]insertUserToDB:user];
                sender.enabled = YES;
                [[Lothar shared]main_setTabBarRootViewController];

            });
        } error:^(RCConnectErrorCode status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                sender.enabled = YES;
                UserInfo.isLogin = NO;

                [self showErrorWithStatus:@"登录失败！"];
            });
        } tokenIncorrect:^{
            //重新请求token,避免无限循环,只重新请求一次,否则失败
            if (_loginFailureTimes < 1) {
                _loginFailureTimes++;
                [self getRY_tokenUserId:user_id deviceToken:token userName:userName userLogo:userLogo sender:sender];
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    sender.enabled = YES;
                    UserInfo.isLogin = NO;
                    [self showErrorWithStatus:@"登录失败！"];
                    
                });
            }
        }];
        
    } failure:^(NSError *error, NSString *info) {
        sender.enabled = YES;
    }];
}


- (IBAction)forgetPasswordAction:(UIButton *)sender {
    XLForgetPwdViewController *vc = [[XLForgetPwdViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)textFieldDidChange:(NSNotification *)notification {
    if ([self.usernameTextField isNotEmptyString] && [self.passwordTextField isNotEmptyString]) {
        self.loginButton.enabled = YES;
    } else {
        self.loginButton.enabled = NO;
    }
}
- (IBAction)configAction:(id)sender {
    XLConfigViewController *viewController = [[XLConfigViewController alloc]init];
    [self.navigationController pushViewController:viewController animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
